import {_decorator, Component, find, isValid, Node} from 'cc';
import {ResourceUtil} from '../util/ResourceUtil';
import {logUtil} from "../util/logUtil";
import {Constant} from '../../config/Constant';

const {ccclass} = _decorator;

@ccclass('UiManager')
export class UiManager extends Component {
    //加载后的面板
    private _dictSharedPanel: any = {}
    //尚未加载判断
    private _dictLoading: any = {}

    private static _instance: UiManager;
    //ui默认根节点
    UIRoot: Node | null = null;

    //日志控制器
    log = logUtil.instance
    logLevel = "UIGame"

    public static get instance() {
        if (this._instance) {
            return this._instance;
        }

        this._instance = new UiManager();
        this._instance.UIRoot = find(Constant.STATIC_NODE_PATH.UI);
        return this._instance;
    }

    /**
     * 显示单例界面
     * @param {String} panelPath
     * @param {Array} args
     * @param {Function} cb 回调函数，创建完毕后回调
     */
    public showDialog(panelPath: string, args: any = [], cb?: Function) {
        if (this._dictLoading[panelPath]) {
            return;
        }
        //路径最后一个
        const scriptName = panelPath.split('/').pop()!;
        const panel = this._dictSharedPanel[panelPath];

        if (panel && isValid(panel)) {
            this._activatePanel(panel, this.UIRoot);
            this._callShowMethod(panel, scriptName, args, cb);
            return;
        }

        this._dictLoading[panelPath] = true;
        ResourceUtil.createUI(panelPath, (err, node) => {
            this._dictLoading[panelPath] = false;
            if (err) {
                console.error(err);
                return;
            }
            this._dictSharedPanel[panelPath] = node;
            this._activatePanel(node, this.UIRoot);
            this._callShowMethod(node, scriptName, args, cb);
        });
    }

    private _activatePanel(panel: Node, parent: Node) {
        panel.parent = parent;
        panel.active = true;
    }

    private _deactivatePanel(panel: Node) {
        panel.parent = null;
        panel.active = false;
    }

    private _callShowMethod(panel: Node, scriptName: string, args: any[], cb?: Function) {
        const script: any = panel.getComponent(scriptName);
        if (script && typeof script.show == 'function') {
            script.show.apply(script, args);
            cb && cb(script);
        } else {
            this.log.log(this.logLevel, `查找不到脚本文件${scriptName}`)
        }
    }

    /**
     * 隐藏单例界面
     * @param {String} panelPath
     * @param {Function} callback
     */
    public hideDialog(panelPath: string, callback?: Function) {
        if (this._dictSharedPanel.hasOwnProperty(panelPath)) {
            let panel = this._dictSharedPanel[panelPath];
            if (panel && isValid(panel)) {
                this._deactivatePanel(panel);
            }
        }
        this._dictLoading[panelPath] = false;
    }
}


